package com.io;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @Author weijingchen
 * @Date 2025/6/16 20:33
 * @Version 1.0.0
 */
public class FileInputStreamTest01 {
    public static void main(String[] args) throws IOException {
        File file = new File("Test/src/main/resources/a.txt");
        test03(file);
    }

    public static void test01(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        int read1 = fis.read(new byte[2]
        );
        int read = fis.read();
        while (read1 != -1) {
            System.out.print((char) read1);
            read1 = fis.read();
        }
        fis.close();
    }

    /**
     * jdk7做法
     * @param file
     * @throws IOException
     */
    public static void test02(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file);
             FileOutputStream fos = new FileOutputStream("Test/src/main/resources/b.txt")) {
            byte[] bytes = new byte[1024];
            int read = fis.read(bytes);
            while (read != -1) {
                System.out.print(new String(bytes, 0, read));
                fos.write(bytes, 0, read);
                read = fis.read(bytes);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 基本做法
     * @param file
     * @throws IOException
     */
    public static void test03(File file) throws IOException {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(file);
            fos = new FileOutputStream("Test/src/main/resources/c.txt");
            byte[] bytes = new byte[1024];
            int read = fis.read(bytes);
            while (read != -1) {
                System.out.print(new String(bytes, 0, read));
                fos.write(bytes, 0, read);
                read = fis.read(bytes);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally{
            if(fis != null){
                fis.close();
            }
            if(fos != null){
                fos.close();
            }
        }
    }

    /**
     * jdk9做法
     * @param file
     * @throws IOException
     */
    public static void test04(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream("Test/src/main/resources/b.txt");
        try (fis;fos) {
            byte[] bytes = new byte[1024];
            int read = fis.read(bytes);
            while (read != -1) {
                System.out.print(new String(bytes, 0, read));
                fos.write(bytes, 0, read);
                read = fis.read(bytes);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
